using System.Collections.Generic;
using ManagedUIFlow.Infrastructure.Flows;

namespace ManagedUIFlow.Infrastructure.Services
{
    public class FlowService 
    {
        private static readonly FlowService Instance = new FlowService();

        public static FlowService Current
        {
            get
            {
                return Instance;
            }
        }

        public virtual Flow GetFlowDefinition(string flowName)
        {
            foreach (var flow in Flows)
                if (string.Compare(flow.Name, flowName, true) == 0)
                    return flow;
            return null;
        }

        public virtual string GetNavigationFor(string flowName, string navigationName, string state)
        {
            if (string.IsNullOrEmpty(state)) return navigationName;

            foreach (var flow in Flows)
                if (string.Compare(flow.Name, flowName, true) == 0)
                    foreach (var navigation in flow.Navigations)
                        if (string.Compare(navigation.Name, navigationName, true) == 0)
                            foreach (var transition in navigation.Transitions)
                                if (string.Compare(transition.State, state, true) == 0)
                                    return transition.NavigateTo;

            return navigationName;
        }

        private IEnumerable<Flow> _flows;
        public virtual IEnumerable<Flow> Flows
        {
            get
            {
                if (_flows == null)
                    _flows = XmlFlowFactory.Flows;

                return _flows;
            }
            set { _flows = value; }
        }
    }
}